﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using TN_CMS.Admin.Helper.Config;

namespace TN_CMS.Admin.Helper.Common
{
    public class MediaHelper
    {
        public static string GetImageUrl(string folder, string imageFullname, int width = 0, int height = 0)
        {
            string url = TN_CMSAdminConfig.GetSettingByKey("Media.Host");
            if (url == null)
            {
                return null;
            }
            string imageName="";
            string extension = "";
            if(ExtractImageExtension(imageFullname,out imageName, out extension))
            {
                url += "/Image/" + imageName;
                if (width > 0)
                    url += "_w" + width;
                if (height > 0)
                    url += "_h" + height;
                url += extension;
                return url;
            }
            return null;
        }

        public static string GetImage(string folder, string imageFullname, int width = 0, int height = 0)
        {
            string url = GetImageUrl(folder, imageFullname, width, height);
            if (url == null)
                return null;

            string result = "";
            WebRequest wrGetUrl = WebRequest.Create(url);

            Stream objStream;
            objStream = wrGetUrl.GetResponse().GetResponseStream();

            StreamReader objReader = new StreamReader(objStream);

            string sLine = "";
            int i = 0;

            while (sLine != null)
            {
                i++;
                sLine = objReader.ReadLine();
                if (sLine != null)
                    result += sLine;
            }
            return result;
        }

        public static bool ExtractImageExtension(string imageFullname, out string imageName, out string extension)
        {
            imageName = "";
            extension = "";
            int lastDotIndex = imageFullname.LastIndexOf('.');
            if (lastDotIndex <= 0 || lastDotIndex == imageFullname.Length - 1)
            {
                return false;
            }
            imageName = imageFullname.Substring(0, lastDotIndex);
            extension = imageFullname.Substring(lastDotIndex);
            return true;
        }
    }
}